IMPORTING AND USING MODULES.
In Python, a module is a file containing Python definitions and statements. It can be used to group related code together and make it reusable across multiple programs. Python has a rich standard library with many built-in modules, and you can also create your own modules. Here's how you can import and use modules in Python:
1. Importing Modules: To use a module in your Python code, you need to import it. There are a few ways to import modules:
a. Import the entire module:
import math
result = math.sqrt(16)
print(result) # Output: 4.0
b. Import specific functions or variables from the module:
from math import sqrt
result = sqrt(16)
print(result) # Output: 4.0
c. Import the module with an alias:
import math as m
result = m.sqrt(16)
print(result) # Output: 4.0
2. Using Module Functions and Variables: Once a module is imported, you can use its functions, classes, and variables in your code. For example, the math
module provides various mathematical functions like sqrt
, sin
, cos
, etc.
import math
x = 5
y = math.sqrt(x)
print(y) # Output: 2.23606797749979
3. Creating Your Own Modules: You can create your own Python modules by creating a new Python file and defining functions, classes, or variables in it. Save the file with a .py
extension to make it a Python module. You can then import and use the functions from this module in other Python files.
mymodule.py
def greet(name):
return f"Hello, {name}!"
main.py
import mymodule
message = mymodule.greet("Alice")
print(message) # Output: Hello, Alice!
Remember to make sure the module file (mymodule.py
in this example) is in the same directory as the file that is importing it, or you should provide the correct path while importing it.
4. Using Standard Library Modules: Python's standard library includes many useful modules that you can use in your code without installing any third-party packages. Some common examples include os
, sys
, random
, datetime
, and csv
. To use these modules, you can import them as shown in the examples above.
In summary, modules are a powerful feature in Python that allow you to organize your code into reusable components and utilize a wide range of built-in functionality. By importing modules, you can access functions and variables from other files, making your code more modular and maintainable.